<!DOCTYPE html>
<html>

<head>
  <title>main</title>
  <script src="Tunnel.js"></script>
</head>

<body style="display:flex;">
  <div id="msg">
    <div><input type="text" id="input"><button onclick="send()">SEND</button></div>
    msg:
  </div>
  <script>
    function randomString(length, chars) {
      var result = '';
      for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
      return result;
    }
    const iframe = document.createElement('iframe');
    const url = location.protocol + '//localhost:9999'
    const signal = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    iframe.src = url + '?from=' + encodeURIComponent(location.origin) + '&signal=' + signal;
    document.body.append(iframe);

    const tunnel = new Tunnel({
      signal: signal,
      origin: url,
      window: iframe.contentWindow,
    })
    tunnel.on('sub', (data) => {
      const msgItem = document.createElement('p');
      msgItem.innerHTML = data
      document.getElementById('msg').append(msgItem)
    })
    function send() {
      tunnel.send('main', document.getElementById('input').value)
    }
  </script>
</body>

</html>